package org.mango.action;

import com.alibaba.fastjson.JSONObject;
import com.xiaoleilu.hutool.io.FileUtil;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.mango.base.BaseAction;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * Created by meigang on 17/9/8.
 */
@RestController
@RequestMapping("/node_engine")
public class NodeEngineAction extends BaseAction{

    @GetMapping("/load")
    public String load(HttpServletRequest request) throws IOException {
        String uri = request.getQueryString();
        String[] marr = uri.split(",");
        StringBuffer sb = new StringBuffer();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        for(String m : marr){
            String module_path = "react/node_modules/";
            //1.先读package.json

            String packageStr = getJarReactStr(resolver, m+"/package.json", module_path);
            JSONObject packageJson = JSONObject.parseObject(packageStr);
            String mainPath = packageJson.getString("main");

            String jsStr = getJarReactStr(resolver, m+"/"+mainPath, module_path);
            //拼上注册的部分
            /**
             * require.register("/js/demo.js", function(module, exports, require){
             *  var obj = {};
                obj.fun1 = function(){
                    alert("it works");
                }
                module.exports = obj;
             * });
             */
            sb.append("require.register(").append("\"").append(m).append("\",function(module,exports,require){")
                    .append(jsStr).append("\r\n").append("});")
                    .append("\r\n");
        }
        return sb.toString();
    }




}
